#include "RemoteCommunicationKit/rcp.h"
#include <cstdint>
#include <multimedia/image_framework/image/image_source_native.h>
#include <stdio.h>

using namespace std;

struct ResponseResult {
    bool g_callback = false;
    Rcp_Response *response = nullptr;
};

// 异步时用的回调，同步不用
void ResponseCallback(void *usrCtx, Rcp_Response *response, uint32_t errCode) {
    (void)usrCtx;
    ResponseResult *temp = (ResponseResult *)usrCtx;
    if (response != NULL) {
        // 从response拿到Buffer，需要进行类型转化
        temp->response = response;

    } else {
        printf("CHEN-----Fetch failed: errCode: %u\n", errCode);
    }
    temp->g_callback = true;
}


Rcp_Response *Request(const char *kHttpServerAddress) {
    Rcp_Request *request = HMS_Rcp_CreateRequest(kHttpServerAddress);
    // 进行http相关请求头的配置
    request->method = RCP_METHOD_GET;
    uint32_t errCode = 0;
    // 创建session
    Rcp_Session *session = HMS_Rcp_CreateSession(NULL, &errCode);
    // 配置请求回调

//     ResponseResult *res = new ResponseResult();
//     Rcp_ResponseCallbackObject responseCallback = {ResponseCallback};
    // 发起请求

    // 异步方式
//     errCode = HMS_Rcp_Fetch(session, request, &responseCallback);
//     // 处理errCode
//     //     if (errCode != 200) {
//     //     }
//     // 等待fetch结果，这里是相当于把异步变为同步，后续可以改造为纯异步，或者使用线程去实现
//     int timeout = 1000;
//     while (timeout-- > 0 && !res->g_callback) {
//         usleep(1000);
//     }

    Rcp_Response *response = HMS_Rcp_FetchSync(session, request, &errCode);
    if (response != NULL) {
        printf("Response status: %d\n", response->statusCode);
    } else {
        printf("Fetch failed: errCode: %u\n", errCode);
    }

    // 在退出前取消可能还在执行的requests
    errCode = HMS_Rcp_CancelSession(session);
    // 清理request
    HMS_Rcp_DestroyRequest(request);
    // 关闭session
    errCode = HMS_Rcp_CloseSession(&session);
    // 处理errCode
    return response;
}


void GetPixelMapFromNet(const char *url, OH_PixelmapNative **pixelMap) {
    Rcp_Response *res = Request(url);
    if (res == nullptr) {
        return;
    }
    // 获取响应体内的结果
    size_t len = res->body.length;
    uint8_t *buffer = (uint8_t *)res->body.buffer;
    // 创建一个空的ImageSource独享，将未解码的字节数组写入
    OH_ImageSourceNative *imageSource = nullptr;
    OH_ImageSourceNative_CreateFromData(buffer, len, &imageSource);

    // todo:这里最好把buffer的资源释放,因为其直接指向res引用
    // res->destroyResponse(res);

    // 解码参数,按照原始参数进行解码，不需要额外参数
    OH_DecodingOptions *options = nullptr;
    OH_DecodingOptions_Create(&options);

    // 从ImageSource创建PixelMap
//     OH_PixelmapNative *pixelMap = nullptr;
    OH_ImageSourceNative_CreatePixelmap(imageSource, options, pixelMap);
    // 释放内存
    OH_DecodingOptions_Release(options);
}
